package com.hardy.leetcode;

/**
 * 最长回文子串问题
 * User: Ruijie Date: 2016/9/7
 */
public class LongestPalindromicSubstring {
    public static String longestPalindrome(String s) {
        int maxLength=0;
        int longestBegin=0;
        for(int i=0;i<s.length();i++){
            for(int j=i;j<s.length();j++){
                if(isHuiWen(s,i,j)){
                    int len=j-i+1;
                    if(maxLength<len){
                        maxLength=len;
                        longestBegin=i;
                    }
                }
            }
        }
        return s.substring(longestBegin,maxLength+longestBegin);
    }

    private static boolean isHuiWen(String s, int start, int end) {
        if(start==end){
            return true;
        }
        while(start<end){
            if(s.charAt(start)!=s.charAt(end)){
                return false;
            }else{
                start++;
                end--;
            }
        }
        return true;
    }

    public static String longestPalindrome1(String s){
        int length=s.length();
        int maxLength=1;
        boolean[][] dp=new boolean[length+1][length+1];
        int start=0;
        for(int i=0;i<length;i++){
            dp[i][i]=true;
            if(i<s.length()-1&&s.charAt(i)==s.charAt(i+1)){
                dp[i][i+1]=true;
                maxLength=2;
                start=i;
            }
        }
        for(int len=3;len<=length;len++){
            for(int i=0;i<=length-len;i++){
                int j=i+len-1;
                if(s.charAt(i)==s.charAt(j)&&dp[i+1][j-1]){
                    dp[i][j]=true;
                    maxLength=len;
                    start=i;
                }
            }
        }
        if(maxLength>=2){
            return s.substring(start,start+maxLength);
        }
        return s;
    }

    public static void main(String[] args) {

        System.out.println(longestPalindrome("abb"));
        System.out.println(longestPalindrome1("abb"));
    }
}
